package com.yyt.threadpooldemo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.NamedThreadLocal;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: yeyangtao
 * @date: 2020/4/13 18:49
 */
@Configuration
public class ThreadPoolConfig {
    @Value("${async.core-pool-size}")
    private Integer corePoolSize;
    @Value("${async.max-pool-size}")
    private Integer maxPoolSize;
    @Value("${async.queue-capacity}")
    private Integer queueCapacity;
    @Value("${async.thread-name-prefix}")
    private String threadNamePrefix;
    @Value("${async.await-time}")
    private Integer awaitTime;


    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //设置线程池中任务的等待时间
        executor.setAwaitTerminationSeconds(awaitTime);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(threadNamePrefix);
        // 设置拒绝策略
        // AbortPolicy: 丢弃任务并抛异常
        // CallerRunsPolicy: 当线程池没有处理能力的时候,调用线程来处理任务
        // DiscardOldestPolicy: 丢弃最前面的任务,重新尝试该任务
        // DiscardPolicy: 丢弃被拒绝的任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        //优雅关机
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}
